package com.tan.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tan.domain.Tag;
import com.tan.domain.response.Result;
import com.tan.domain.response.StatusCode;
import com.tan.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: longshifu
 * @time: 2022/7/17 17:29
 */
@RestController
@Slf4j
@RequestMapping("/admin")
public class TagController {
    @Autowired
    TagService tagService;

    @PostMapping("/tags")
    public Result addTag(@RequestBody Map<String, Tag> param) {
        Tag tag = param.get("tag");
        log.info("请求参数tag: {}", tag);
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", tag.getName());
        Tag t = tagService.getOne(queryWrapper);
        if (t!=null) {
            if (tag.getName().equals(t.getName()) && tag.getBlogId().equals(t.getBlogId())) {
                return new Result(false, StatusCode.ERROR, "不能添加重复的标签", null);
            } else {
                tagService.saveOrUpdate(tag);
            }
        }else {
            tagService.saveOrUpdate(tag);
        }
        Tag resultTag = tagService.getOne(queryWrapper);
        return new Result(true, StatusCode.OK, "添加标签成功", resultTag);
    }
}
